/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package gui.components.basic.gui.generic;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.Id;
import javax.swing.DefaultListModel;

/**
 *
 * @author Luca
 */
public class GenericListModel<T>  extends DefaultListModel<T>{
    
    public Map<Long,T> idMap = new HashMap<Long,T>();
    private Field idField = null;
    
    public GenericListModel() {
        super();
    }
    
//    public void refresh(){
//        this.removeAllElements();
//        PersonJpaController cc = new PersonJpaController(Persistence.createEntityManagerFactory("dbAnagBasePU"));
//            List<Person> findPersonEntities = cc.findPersonEntities();
//            for (Person person : findPersonEntities) {
//                idMap.put(person.getId(), person);
//                this.addElement(person);
//            }
//    }

    @Override
    public void addElement(T element) {
        try {
            super.addElement(element);
            idMap.put(getIDFromEntity(element), element);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(GenericListModel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    
    private Long getIDFromEntity(T entity) throws IllegalAccessException{
        if(idField == null){
            Field[] declaredFields = entity.getClass().getDeclaredFields();
                for (Field field : declaredFields) {
                    Id idAnnotation = field.getAnnotation(Id.class);
                    if (idAnnotation != null) {
                        System.out.println("ID FOUND");
                        field.setAccessible(true);
                        this.idField = field;
                    }
                }
        }
        Long id = (Long)idField.get(entity);
        return id;
    }

     public void updateEntity(T newPerson) {
        try {
            T oldPerson;
            oldPerson = idMap.get(getIDFromEntity(newPerson));
            int indexOf = this.indexOf(oldPerson);
            System.out.println("index = " + indexOf);
            this.remove(indexOf);
            this.add(indexOf, newPerson);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(GenericListModel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
}
